package com.snail;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

public class PdfToImageConverterGUI extends JFrame {
    private JTextField pdfFilePathField;
    private JTextField outputImagePathField;
    private static final String[] OUTPUT_FORMATS = {"jpg", "jpeg", "png"};
    private static final Integer[] DPI_OPTIONS = {300, 600, 900};

    public PdfToImageConverterGUI() {
        setTitle("PDF转图片（刘海良）");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 250);
        setLocationRelativeTo(null);

        JComboBox<String> formatComboBox = new JComboBox<>(OUTPUT_FORMATS);
        JLabel formatLabel = new JLabel("输出格式:");

        // 添加分辨率选择框
        JComboBox<Integer> dpiComboBox = new JComboBox<>(DPI_OPTIONS);
        JLabel dpiLabel = new JLabel("分辨率:");



        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(5, 5, 5, 5);

        JLabel pdfFilePathLabel = new JLabel("PDF文件:");
        pdfFilePathField = new JTextField(60);
        JButton selectPdfFileButton = new JButton("选择");
        selectPdfFileButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileFilter(new PDFFileFilter());
                int result = fileChooser.showOpenDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    pdfFilePathField.setText(selectedFile.getAbsolutePath());
                }
            }
        });

        JLabel outputImagePathLabel = new JLabel("图片保存位置(默认与PDF同一位置):");
        outputImagePathField = new JTextField(60);
        JButton selectOutputImageButton = new JButton("选择");
        selectOutputImageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                int result = fileChooser.showSaveDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    outputImagePathField.setText(selectedFile.getAbsolutePath());
                }
            }
        });

        JButton convertButton = new JButton("转换");
        convertButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String pdfFilePath = pdfFilePathField.getText();
                if ("".equals(pdfFilePath)){
                    JOptionPane.showMessageDialog(PdfToImageConverterGUI.this, "请选择PDF文件", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                String outputFormat = (String) formatComboBox.getSelectedItem();
                if ("".equals(outputFormat)){
                    outputFormat = "jpg";
                }
                String outputImagePath = outputImagePathField.getText();
                if ("".equals(outputImagePath)){
                    String baseName = pdfFilePath.substring(0, pdfFilePath.lastIndexOf('.'));
                    outputImagePath = baseName + "." + outputFormat;
                }
                try {
                    PDDocument document = PDDocument.load(new File(pdfFilePath));
                    PDFRenderer pdfRenderer = new PDFRenderer(document);
                    pdfRenderer.setSubsamplingAllowed(false);
                    // 设置渲染选项，包括分辨率
                    RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                    hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                    hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    pdfRenderer.setRenderingHints(hints);
                    int dpi = (Integer) dpiComboBox.getSelectedItem();
                    System.out.println("===================>dpi:"+dpi);
                    int totalHeight = 0;
                    int maxWidth = 0;

                    for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
                        BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, dpi, ImageType.RGB); // 设置分辨率为300

                        totalHeight += image.getHeight();
                        maxWidth = Math.max(maxWidth, image.getWidth());
                    }

                    BufferedImage combinedImage = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics = combinedImage.createGraphics();

                    int currentHeight = 0;

                    for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
                        BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, dpi); // 设置分辨率为300

//                        graphics.drawImage(image, 0, currentHeight, null);
//                        currentHeight += image.getHeight();

                        // 创建一个新的图像，宽度为最大宽度，高度不变，用于填充
                        BufferedImage paddedImage = new BufferedImage(maxWidth, image.getHeight(), BufferedImage.TYPE_INT_ARGB);
                        Graphics2D paddedGraphics = paddedImage.createGraphics();

                        // 填充白色背景
                        paddedGraphics.setColor(Color.WHITE);
                        paddedGraphics.fillRect(0, 0, maxWidth, image.getHeight());

                        // 计算在新图像上的x坐标，以便居中放置原始图像（如果需要居中，否则直接贴左边）
                        int centerX = (maxWidth - image.getWidth()) / 2;
                        paddedGraphics.drawImage(image, centerX, 0, null); // 这里假设居中，根据需要调整

                        paddedGraphics.dispose();

                        // 在组合图像上绘制填充后的图像
                        graphics.drawImage(paddedImage, 0, currentHeight, null);
                        currentHeight += image.getHeight();
                    }

                    graphics.dispose();

                    ImageIO.write(combinedImage, outputFormat, new File(outputImagePath));

                    document.close();

                    JOptionPane.showMessageDialog(null, "转换完成!");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "转换失败!");
                }
            }
        });

        constraints.gridx = 0;
        constraints.gridy = 0;
        mainPanel.add(pdfFilePathLabel, constraints);

        constraints.gridx = 2;
        constraints.gridy = 0;
//        constraints.weightx = 1.0;
        mainPanel.add(pdfFilePathField, constraints);

        constraints.gridx = 1;
        constraints.gridy = 0;
        mainPanel.add(selectPdfFileButton, constraints);

        constraints.gridx = 0;
        constraints.gridy = 1;
        mainPanel.add(outputImagePathLabel, constraints);

        constraints.gridx = 2;
        constraints.gridy = 1;
        mainPanel.add(outputImagePathField, constraints);

        constraints.gridx = 1;
        constraints.gridy = 1;
        mainPanel.add(selectOutputImageButton, constraints);

        constraints.gridx = 0;
        constraints.gridy = 3;
        mainPanel.add(formatLabel, constraints);

        constraints.gridx = 1;
        constraints.gridy = 3;
        mainPanel.add(formatComboBox, constraints);

        constraints.gridx = 0;
        constraints.gridy = 4;
        mainPanel.add(dpiLabel, constraints);

        constraints.gridx = 1;
        constraints.gridy = 4;
        mainPanel.add(dpiComboBox, constraints);

        constraints.gridx = 1;
        constraints.gridy = 8;
        constraints.gridwidth = 2;
        mainPanel.add(convertButton, constraints);



        add(mainPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                PdfToImageConverterGUI converterGUI = new PdfToImageConverterGUI();
                converterGUI.setVisible(true);
            }
        });
    }
}
